package com.ruoyi.partybuilding.controller;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import com.easy.query.core.basic.jdbc.tx.Transaction;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.partybuilding.common.*;
import com.ruoyi.partybuilding.domain.SysUserRef;
import com.ruoyi.partybuilding.domain.SysUserRoleRef;
import com.ruoyi.partybuilding.domain.vo.UserMemberVo;
import com.ruoyi.partybuilding.service.impl.MemberServiceImpl;
import com.ruoyi.partybuilding.service.impl.OrgServiceImpl;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.var;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.partybuilding.domain.Member;
import com.ruoyi.partybuilding.service.IMemberService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import static cn.hutool.json.XMLTokener.entity;

/**
 * 党员信息Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "党员信息")
@RestController
@RequestMapping("/partybuilding/Member")
public class MemberController extends EQueryController<Member>
{
    @Autowired
    private MemberServiceImpl memberService;

    @Resource
    ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;
    @Resource
    OrgServiceImpl orgService;
    /**
     * 查询党员信息列表
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:list')")
    @GetMapping("/list")
    @DataScope
    public TableDataInfoRows<UserMemberVo> list(UserMemberVo entity, PageSort pageRequest) {
        var page = queryVo(entity, pageRequest);
        return toTableDataInfoRows(page);
    }
    @ApiOperation(value = "党员信列表获取，无权限过滤",notes = "includeSubsDept表示是否要查询下级的人员true表示查询，默认不查")
    @GetMapping("/memberList")
    public R<List<UserMemberVo>> memberList(UserMemberVo entity,Boolean includeSubsDept) {
        var list = memberService.queryVo(entity, includeSubsDept != null && includeSubsDept, PageSort.toMaxSize());
        return R.ok(list.getContent());
    }

    @ApiOperation("党员信息扁平化,过滤逻辑删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:list')")
    @GetMapping("/queryVo")
    public R<Page<UserMemberVo>> queryVo(UserMemberVo vo,PageSort pageRequest) {
        var page = memberService.queryVo(vo, false, pageRequest);
        orgService.deptSet(page.getContent(), (p, p2) -> p2.setDeptName(p.getDeptName()));
        return R.ok(page);
    }

    /**
     * 导出党员信息列表
     */
    @ApiOperation("导出")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:export')")
    @Log(title = "党员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @DataScope
    public void export(HttpServletResponse response, UserMemberVo member) {
        var re = queryVo(member, PageSort.toMaxSize());
        if (!R.isSuccess(re))
            return;
        var list = re.getData().getContent();
        var util = new ExcelUtil<>(UserMemberVo.class);
        util.exportExcel(response, list, "党员信息数据");
    }
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    ISysRoleService sysRoleService;
    @ApiOperation("导入")
    @Log(title = "党员信息", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public R importData(MultipartFile file) throws Exception {

        var util = new ExcelUtil<UserMemberVo>(UserMemberVo.class);
        List<UserMemberVo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        //验证用户名称
        var lnames = userList.stream().map(p -> p.getUserName()).collect(Collectors.toList());
        var ulist = queryHelper.queryable(SysUserRef.class).where(p -> p.in(SysUserRef::getUserName, lnames)).toList();
        if (ulist.size() > 0) {
            return R.fail("登录名重复");
        }

        for (var item : userList) {
            var user = new SysUserRef();
            user.setStatus("0");
            BeanUtils.copyProperties(item, user);
            user.setUserId(null);
            item.setUser(user);
            item.setId(null);
            item.setPassword("123456");
            item.setName(item.getNickName());
            var re = checkUser(user);
            if (re != null) return re;


        }
        var users = userList.stream().map(p -> p.getUser()).collect(Collectors.toList());
        var list = sysRoleService.selectRoleList(new SysRole() {{
            setRoleKey("common");
        }});
        SysRole role = null;
        if (!list.isEmpty()) {
            var tmp = list.stream().filter(p -> "common".equals(p.getRoleKey())).findFirst();
            if (tmp.isPresent())
                role = tmp.get();
        }

        try (Transaction transaction = queryHelper.query().beginTransaction()) {
            queryHelper.query().insertable(users).executeRows(true);
            userList.forEach(p -> p.setUserId(p.getUser().getUserId()));
            var mList = userList.stream().map(p -> DataUtil.copyProperties(p, new Member())).collect(Collectors.toList());
            queryHelper.query().insertable(mList).executeRows();//memberService.insertMember(member)
            if (role != null) {
                var roleId = role.getRoleId();
                var lists = new ArrayList<SysUserRoleRef>();
                users.forEach(p -> {
                    var tmp = new SysUserRoleRef();
                    tmp.setRoleId(roleId);
                    tmp.setUserId(p.getUserId());
                    lists.add(tmp);
                });
                queryHelper.query().insertable(lists).executeRows();
            }
            transaction.commit();
        }
        return R.ok();
    }
    @ApiOperation("导入模板下载")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        var util = new ExcelUtil<>(UserMemberVo.class);
        util.importTemplateExcel(response, "党员数据");
    }

    /**
     * 获取党员信息详细信息
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:query')")
    @GetMapping(value = "/{id}")
    public R<Member> getInfo(@PathVariable("id") Long id) {
        var member = queryHelper.query().queryable(Member.class).include(p -> p.one(Member::getUser)).where(p -> p.eq(Member::getId, id)).firstOrNull();
        return R.ok(member);
    }



    /**
     * 新增党员信息
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:add')")
    @Log(title = "党员信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R add(@RequestBody Member member) {
        var user = member.getUser();
        if (user == null)
            return R.fail("用户不能为空");

        R<Object> userRe = checkUser(user);
        if (userRe != null) return userRe;

        try (Transaction transaction = queryHelper.query().beginTransaction()) {
            queryHelper.query().insertable(user).executeRows(true);
            //var newUser=queryHelper.query().queryable(SysUser.class).where(p->p.eq(SysUser::getUserName,user.getUserName())).firstOrNull();
            member.setUserId(user.getUserId());
            queryHelper.query().insertable(member).executeRows();//memberService.insertMember(member)
            transaction.commit();
        }
        return R.ok();
    }
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:query')")
    @GetMapping(value = "/checkInfo")
    public R checkInfo(SysUser user){
        var re=checkUser(user);
        if(re==null)
            return R.ok();
        return R.ok(re.getCode(),re.getMsg());
    }
    private R<Object> checkUser(SysUser user) {
        if (!sysUserService.checkUserNameUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysUserService.checkEmailUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword("123456");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setStatus("0");
        user.setCreateTime(new Date());
        return null;
    }

    /**
     * 修改党员信息
     */
    @ApiOperation("编辑")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:edit')")
    @Log(title = "党员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional
    public R edit(@RequestBody Member member) {
        var memberOld = queryHelper.query().queryable(Member.class).include(p -> p.one(Member::getUser)).where(p -> p.eq(Member::getUserId, member.getUserId())).firstOrNull();
        if (memberOld == null)
            return R.fail("用户不存在");
        //用户更新
        var user = memberOld.getUser();
        if (member.getUser() != null) {
            user.setNickName(member.getUser().getNickName());
            user.setSex(member.getUser().getSex());
            user.setAvatar(member.getUser().getAvatar());
            user.setDeptId(member.getUser().getDeptId());
            user.setPhonenumber(member.getUser().getPhonenumber());
            user.setStatus(member.getUser().getStatus());
            member.toUserSet(user);
            sysUserService.updateUserProfile(user);
        }
        //党员更新
        member.setUserId(user.getUserId());
        queryHelper.query().updatable(member).executeRows();
        return R.ok();
    }
    @ApiOperation("编辑履历")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:edit')")
    @Log(title = "党员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editResume")
    public R editResume(@RequestBody Member member){
            var info=queryHelper.queryable(Member.class).whereById(member.getId()).firstOrNull();
            info.setResume(member.getResume());
            var re=queryHelper.query().updatable(info).executeRows();
            return R.ok();

    }


    @ApiOperation("逻辑删除，将逻辑删除用户")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:remove')")
    @Log(title = "党员信息", businessType = BusinessType.DELETE)
    @PostMapping("logicDel/{userId}")
    public R logicDel(@PathVariable Long userId)
    {
        var member=queryHelper.query().queryable(Member.class).include(p->p.one(Member::getUser)).where(p->p.eq(Member::getUserId,userId)).firstOrNull();
        if(member==null)
            return R.fail("党员不存在");
        sysUserService.deleteUserById(userId);

        return R.ok();
    }
    @ApiOperation("启停用户账号，修改状态")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:edit')")
    @Log(title = "党员信息", businessType = BusinessType.UPDATE)
    @PostMapping("stopMember/{userId}")
    public R stopMember(@PathVariable Long userId,Boolean onoff) {
        var member = queryHelper.query().queryable(Member.class).include(p -> p.one(Member::getUser)).where(p -> p.eq(Member::getUserId, userId)).firstOrNull();
        if (member == null)
            return R.fail("党员不存在");
        if (onoff == null)
            return R.fail("启停状态错误");
        var user = new SysUser();
        user.setStatus("" + (onoff ? 1 : 0));
        sysUserService.updateUserStatus(user);

        return R.ok();
    }
    /**
     * 删除党员信息
     */
    @ApiOperation(value = "删除",notes = "已改为逻辑删除，与logicDel相同")
    @PreAuthorize("@ss.hasPermi('partybuilding:Member:remove')")
    @Log(title = "党员信息", businessType = BusinessType.DELETE)
	@PostMapping("remove/{userId}")
    public R remove(@PathVariable Long userId)
    {
        return logicDel(userId);

    }
}
